package com.kkb.controller;

import com.kkb.domain.AjaxResult;
import com.kkb.pojo.TUser;
import com.kkb.service.UserService;
import com.kkb.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Enumeration;

import static com.kkb.constant.GlobalConst.SESSION_KEY_USER;

@Controller
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    //登录页面
    @PostMapping("/user/login")
    @ResponseBody
    public AjaxResult login(@Validated @RequestBody TUser loginForm) {
        //根据用户名获取用户对象
        TUser user = userService.findByUserName(loginForm.getUsername());
        // 判断用户对象是否为空
        if (user == null) {
            return AjaxResult.error("用户名错误");
        }
        // 判断用户密码是否一致
        if (user.getPassword().equals(loginForm.getPassword())) {
            // 把用户对象放入session中
            ServletUtils.getSession().setAttribute(SESSION_KEY_USER, user);
            return AjaxResult.success("登录成功");
        } else {
            return AjaxResult.error("用户名或密码错误");
        }
    }

    //退出登录 * 清除所有会话信息 * 返回json
    @GetMapping("/user/logout")
    @ResponseBody
    public AjaxResult logout() {
        Enumeration<String> names = ServletUtils.getSession().getAttributeNames();
        while (names.hasMoreElements()) { //如果session里有值，就清除
            ServletUtils.getSession().removeAttribute(names.nextElement().toString());
        }
        return AjaxResult.success("退出成功");
    }
}
